package cn.kgc.shiro.web.controller;

import cn.kgc.shiro.web.entity.User;
import cn.kgc.shiro.web.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/6/4
 * @description   localhost:8080/hello/m1        localhost/hello/m1
 */
@RestController
@RequestMapping("user")
public class  UserController {

    @Resource
    private UserService userService;


    @RequestMapping("register")
    public Map<String,Object> registerUser(User user){

        return userService.registerUser(user);
    }


    @RequestMapping("login")
    public Map<String,Object> login(User user){

        Subject subject = SecurityUtils.getSubject();
        HashMap<String, Object> result = new HashMap<>();
        try {
            subject.login(new UsernamePasswordToken(user.getUsername(),user.getPassword()));
            result.put("code",0);
            result.put("message","认证通过");
        }catch (UnknownAccountException e){
            result.put("code",110);
            result.put("message","用户名错误");
        }catch (IncorrectCredentialsException e){
            result.put("code",110);
            result.put("message","密码错误");
        }

        return result;
    }


    @RequestMapping("list")
    public List<User> userList(){

        List<User> list = userService.list();
        return list;
    }

    @RequestMapping("add")
    public Map<String,Object> addUser(){

        HashMap<String, Object> result = new HashMap<>();
        result.put("code",0);
        result.put("message","添加成功");
        return result;
    }

    @RequestMapping("update")
    @RequiresRoles(value = {"admin","super"},logical = Logical.OR)   //  注解式权限控制
    // @RequiresPermissions()
    public Map<String,Object> updateUser(){
        HashMap<String, Object> result = new HashMap<>();
        result.put("code",0);
        result.put("message","更新成功");
        return result;
    }


    //  admin
    @RequestMapping("delete")
    public Map<String,Object> deleteUser(){


        Subject subject = SecurityUtils.getSubject();
        boolean b = subject.hasRole("admin");
        HashMap<String, Object> result = new HashMap<>();
        if (b){
            result.put("code",0);
            result.put("message","删除成功");
        }else {
            result.put("code",403);
            result.put("message","没有权限，请联系管理员");
        }

        return result;
    }
}
